﻿using System.Threading;

namespace ESoft.Helpers
{
    /// <summary>
    /// 原子锁帮助类
    /// </summary>
    public class InterlockedHelper
    {
        /// <summary>
        /// 原子加1
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int Increment(ref int value)
        {
            return Interlocked.Increment(ref value);
        }

        /// <summary>
        /// 原子减1
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int Decrement(ref int value)
        {
            return Interlocked.Decrement(ref value);
        }

        /// <summary>
        /// 原子替换 刚抢到时值不变，其他未抢到的为变后的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public object Exchange(ref object key, object value)
        {
            return Interlocked.Exchange(ref key, value);
        }

        /// <summary>
        /// 原子比较 再替换
        /// </summary>
        /// <param name="o"></param>
        /// <param name="value"></param>
        /// <param name="result"></param>
        public void CompareExchange(ref object o, object value, object result)
        {
            Interlocked.CompareExchange(ref o, value, result);
        }
    }
}